package com.simen.connectandroid.command;

import com.simen.connectandroid.Launcher;
import com.simen.connectandroid.command.utils.CommandCreator;
import com.simen.connectandroid.model.Device;
import com.simen.connectandroid.model.DeviceIp;
import com.simen.connectandroid.model.DeviceIpStatus;
import com.simen.hellobytes.log.Log;
import com.simen.hellobytes.runtime.RuntimeHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * Created on 2021/10/30 16:39.
 *
 * @author Simen
 */
public class GetIpCommand extends AdbCommand<GetIpCommand> {

    private static final String TAG = GetIpCommand.class.getSimpleName();
    private List<DeviceIp> deviceIpList = new ArrayList<DeviceIp>();
    private boolean execResult;

    public GetIpCommand(Device device) {
        super(device);
    }

    @Override
    public GetIpCommand exec() {
        RuntimeHelper runtimeHelper = RuntimeHelper.create(CommandCreator.createAdb()
                .appendAdbDevice(device)
                .appendParam("shell netcfg")
                .build());
        runtimeHelper.exec();

        execResult = runtimeHelper.getProcessCode() == 0;
        log = runtimeHelper.getOutputLog();

        Log.i(TAG, runtimeHelper.command());
        Log.i(TAG, log);

        if (execResult) {
            String[] lines = log.split("\n");
            if (lines.length > 1) {
                for (int i = 1; i < lines.length; i++) {
                    String[] params = RuntimeHelper.splitCommand(lines[i]);
                    if (params.length == 4) {
                        DeviceIp deviceIp = new DeviceIp()
                                .setNet(params[0])
                                .setStatus(DeviceIpStatus.parse(params[1]))
                                .setAddress(params[2])
                                .setHex(params[3]);

                        deviceIpList.add(deviceIp);
                    } else {
                        Log.e(TAG, "unknown format: " + lines[i]);
                    }
                }
            }
        }
        return this;
    }

    @Override
    public boolean execResult() {
        return execResult;
    }

    public List<DeviceIp> getDeviceIpList() {
        return deviceIpList;
    }

    /**
     * @return 返回可用的局域网信息
     */
    public DeviceIp getConnectableDeviceIp() {
        for (int i = 0; i < deviceIpList.size(); i++) {
            if ("wlan0".equalsIgnoreCase(deviceIpList.get(i).getNet())) {
                return deviceIpList.get(i);
            }
        }

        return null;
    }
}
